package com.frostmourne.mxsattributeinventory.modules.extra;

import com.frostmourne.mxsattributeinventory.MXSAttributeInventory;
import com.gitee.mxstars.builder.ItemBuilder;
import com.gitee.mxstars.mxscript.MXScriptExtra;
import com.gitee.mxstars.utils.CommonUtil;
import org.apache.commons.lang3.tuple.MutablePair;
import org.apache.commons.lang3.tuple.Pair;
import org.bukkit.Material;
import org.bukkit.command.CommandSender;
import org.bukkit.event.inventory.InventoryClickEvent;
import org.bukkit.inventory.ItemStack;

import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

public class DefaultCurrentType extends MXScriptExtra {
    @Override
    public Map<String, Pair<Class<?>, Method>> extraScript() {
        Class<?> scriptClass = DefaultCurrentType.class;
        Map<String, Pair<Class<?>,Method>> scriptList = new HashMap<>();
        Method method;
        try {
            method = scriptClass.getDeclaredMethod("defaultCurrentType",CommandSender.class, String.class, InventoryClickEvent.class);
        } catch (NoSuchMethodException e) {
            throw new RuntimeException(e);
        }
        Pair<Class<?>,Method> pair = new MutablePair<>(scriptClass,method);
        scriptList.put("DEFAULT-CURRENT-TYPE",pair);


        return scriptList;
    }

    public static void defaultCurrentType(CommandSender commandSender,String type , InventoryClickEvent event){

        ItemStack item = event.getCurrentItem();
        if (item == null){
            return;
        }
        int slot = event.getRawSlot();
        String invName = MXSAttributeInventory.titleMap.get(event.getView().getTitle());
        if (MXSAttributeInventory.inventoryMap.get(invName).getInv().getItem(slot) != null &&
                MXSAttributeInventory.inventoryMap.get(invName).getInv().getItem(slot).isSimilar(item)){
            if (type==null){
                return;
            }
            if (type.equalsIgnoreCase("Air") || CommonUtil.isNum(type) && Integer.parseInt(type) == 0){
                item.setAmount(0);
                return;
            }
            Material material = new ItemBuilder(type).getItem().getType();
            if (material != null){
                item.setType(material);
            }
        }
    }

}

